package com.example.demo.controller;

import com.example.demo.dao.Jpa.AccountDAO;
import com.example.demo.entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: 李浩然
 * @Date: 2021/4/26 3:06 下午
 */
@RestController
@RequestMapping("/accountJpa")
public class JpaController {
    @Autowired
    AccountDAO accountDao;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public List<Account> getAccounts() {
        return accountDao.findAll();
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Account getAccountById(@PathVariable("id") int id) {
        return accountDao.findById(id).get();
    }

    @RequestMapping(value = "{id}", method = RequestMethod.PUT)
    public String updateAccount(@PathVariable("id") int id, @RequestParam(value = "name", required = true) String name, @RequestParam(value = "money", required = true) double money) {
        Account account = new Account();
        account.setId(id);
        account.setName(name);
        account.setMoney(money);
        Account account1 = accountDao.saveAndFlush(account);
        return account1.toString();
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    public String postAccount(@RequestParam(value = "name", required = true) String name, @RequestParam(value = "money", required = true) double money) {
        Account account = new Account();
        account.setMoney(money);
        account.setName(name);

        Account account1 = accountDao.save(account);
        return account1.toString();
    }

}
